package com.wxhandle.cleandemo.oauth.config;

import java.security.Principal;
import java.util.Optional;

import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class AuditorAwareImpl implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
     
       if (authentication == null || !authentication.isAuthenticated()) {
        return null;
       }
       Object principal = authentication.getPrincipal();

       if (principal instanceof UserDetails) {
 
          return Optional.of(((UserDetails) principal).getUsername());
 
       }
 
       if (principal instanceof Principal) {
 
          return Optional.of(((Principal) principal).getName());
       }
       return Optional.of(authentication.getName());
    }

 }